package s6_lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Account {
    private String name;
    private String id;
    private double money;
    private final Lock lock = new ReentrantLock();//final 保护锁

    public Account() {
    }

    public Account(String id, double money) {
        this.id = id;
        this.money = money;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public double getMoney() {
        return money;
    }

    public synchronized void setMoney(double money) {
        this.money = money;
    }

    public void draw(double money) {
        String name1 = Thread.currentThread().getName();
        lock.lock();
        try {
            if (this.money >= money) {
                System.out.println(name1 + "取钱成功，取钱数目：" + money);
                this.money -= money;
                System.out.println("余额：" + this.money);
            } else {
                System.out.println(name1 + "取钱失败，余额不足！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
